package com.stud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stud.common.enums.WorkflowDefinitionEnum;
import com.stud.common.mybatis.BaseServiceImpl;
import com.stud.common.utils.Toolkit;
import com.stud.system.domain.WorkflowDefinition;
import com.stud.system.mapper.WorkflowDefinitionMapper;
import com.stud.system.service.WorkflowDefinitionService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 流程定义Service业务层处理
 *
 * @author Stud
 * @date 2023-03-06
 */
@Service
public class WorkflowDefinitionServiceImpl extends BaseServiceImpl<WorkflowDefinitionMapper, WorkflowDefinition> implements WorkflowDefinitionService {

    @Override
    public boolean add(WorkflowDefinition workflowDefinition) {
        LambdaQueryWrapper<WorkflowDefinition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkflowDefinition::getDefinitionCode, workflowDefinition.getDefinitionCode());
        queryWrapper.orderByDesc(WorkflowDefinition::getVersion);
        queryWrapper.last(" limit 1 ");
        WorkflowDefinition oldVersion = this.getOne(queryWrapper);

        if (Objects.nonNull(oldVersion)) {
            workflowDefinition.setVersion(Toolkit.object2Int(oldVersion.getVersion()) + 1);
            oldVersion.setFlag("1");
            this.update(oldVersion);
        }

        return this.save(workflowDefinition);
    }

    @Override
    public WorkflowDefinition getByDefinitionEnum(WorkflowDefinitionEnum workflowDefinitionEnum) {
        LambdaQueryWrapper<WorkflowDefinition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkflowDefinition::getDefinitionCode, workflowDefinitionEnum);
        return getOne(queryWrapper);
    }
}
